package com.lutzyt.delivery.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lutzyt.delivery.bean.Order;
import com.lutzyt.delivery.bean.OrderComment;
import com.lutzyt.delivery.mapper.OrderCommentDAO;
import com.lutzyt.delivery.service.OrderCommentService;
import com.lutzyt.delivery.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author zyt
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class OrderCommentServiceImpl extends ServiceImpl<OrderCommentDAO, OrderComment> implements OrderCommentService {

  private OrderCommentDAO orderCommentDAO;
  private OrderService orderService;

  @Transactional(readOnly = true)
  @Override
  public OrderComment findById(Integer id) {
    return orderCommentDAO.selectById(id);
  }

  @Transactional(readOnly = true)
  @Override
  public IPage<OrderComment> findByPage(int pageNum, int pageSize) {
    return orderCommentDAO.selectPage(new Page<>(pageNum, pageSize), null);
  }

  @Override
  public void insert(OrderComment orderComment) {
    orderCommentDAO.insert(orderComment);
  }

  @Override
  public void update(OrderComment orderComment) {
    orderCommentDAO.updateById(orderComment);
  }

  @Override
  public void deleteById(Integer id) {
    orderCommentDAO.deleteById(id);
  }

  @Override
  public OrderComment findByOrderId(Integer id) {
    final OrderComment orderComment = this.lambdaQuery()
        .eq(OrderComment::getDeleted, 0)
        .eq(OrderComment::getOrderId, id)
        .eq(OrderComment::getState, "PASS")
        .one();
    return orderComment;
  }

  @Override
  public List<OrderComment> findByCustomerId(Integer id) {
    final List<OrderComment> orderComments = this.lambdaQuery()
        .eq(OrderComment::getDeleted, 0)
        .eq(OrderComment::getCustomerId, id)
        .list();
    orderComments.forEach(this::setOrder);
    return orderComments;
  }

  private void setOrder(OrderComment orderComment){
    final Order order = orderService.findById(orderComment.getOrderId());
    orderComment.setOrder(order);
  }

  @Override
  public String getAuditField() {
    return "state";
  }

  @Autowired
  public void setOrderService(OrderService orderService) {
    this.orderService = orderService;
  }

  @Autowired
  public void setOrderCommentDAO(OrderCommentDAO orderCommentDAO) {
    this.orderCommentDAO = orderCommentDAO;
  }
}